/**
 * @author: chanzhugang
 * @create: 2021/03/21 17:38
 */

package com.geek;

/**
 * @author: chanzhugang
 * @create: 2021/03/21 17:38 
 */
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 自定义一个 Classloader，加载一个 Hello.xlass 文件，执行 hello 方法，此文件内容是一个 Hello.class 文件所有字节（x=255-x）处理后的文件
 */
public class CustomClassLoader extends ClassLoader {

    public static void main(String[] args) {
        Class<?> hello = new CustomClassLoader().findClass("Hello");
        Method method;
        try {
            method = hello.getDeclaredMethod("hello");
            // 构造获取实例对象
            method.invoke(hello.getConstructor().newInstance());
       //     method.invoke(hello.newInstance());
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        System.out.println("commit 1");
        System.out.println("commit 2");
        System.out.println("commit 3");
    }


    @Override
    protected Class<?> findClass(String name) {
        String filePath = "/Users/chanzhugang/Desktop/study/homework/week01/src/com/geek/Hello.xlass";
        File file = new File(filePath);
        Path path = Paths.get(file.getAbsolutePath());
        byte[] bytes = null;
        try {
            bytes = Files.readAllBytes(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = (byte) (255 - bytes[i]);
        }
        return defineClass(name, bytes, 0, bytes.length);
    }
}